package com.glp.work.flow.controller;

import com.glp.common.reponse.BaseResult;
import com.glp.work.flow.demo.service.UserDemoService;
import com.glp.work.flow.mapper.WfFormTimeConsumingMapper;
import com.glp.work.flow.pojo.UserDemo;
import com.glp.work.flow.request.WfOrderQueryDTO;
import com.glp.work.flow.service.client.PermissionClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.constants.BpmnXMLConstants;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.common.engine.impl.util.IoUtil;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserDemoController
 * @Description: TODO
 * @Author ywguo
 * @Date 2020/6/2 15:00
 * @Version V1.0
 **/
@RestController
@Slf4j
@RequestMapping("/userDemo")
@Api(tags = "工作流demo")
public class UserDemoController {

    @Resource
    private UserDemoService userDemoService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PermissionClient permissionService;
    @Resource
    private WfFormTimeConsumingMapper wfFormTimeConsumingMapper;
    @Resource
    private HistoryService historyService;
    @Autowired
    private ProcessEngine processEngine;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private RepositoryService repositoryService;

    /**
     * 代办列表
     *
     * @MethodName: userDemoAgency
     * @Description: TODO
     * @Param: []
     * @Return: com.glp.common.reponse.BaseResult
     * @Author: ywguo
     * @Date: 2020/6/2
     **/
    @ApiOperation("待办列表")
    @PostMapping("/userDemoAgencyList")
    public BaseResult userDemoAgencyList(@RequestBody WfOrderQueryDTO wfOrderQueryDTO) {
        return new BaseResult<>(200, "成功", userDemoService.userDemoAgencyList(wfOrderQueryDTO));
    }

    /**
     * 已办列表
     *
     * @MethodName: userDemoAgency
     * @Description: TODO
     * @Param: []
     * @Return: com.glp.common.reponse.BaseResult
     * @Author: ywguo
     * @Date: 2020/6/2
     **/
    @ApiOperation("已办工单")
    @PostMapping("/userDemoDone")
    public BaseResult userDemoDone(@RequestBody WfOrderQueryDTO wfOrderQueryDTO) {
        return new BaseResult<>(200, "成功", userDemoService.userDemoDone(wfOrderQueryDTO));
    }

    /**
     * 添加一个事件流
     *
     * @MethodName: inserUserDemo
     * @Description: TODO
     * @Param: [userDemo]
     * @Return: java.lang.String
     * @Author: ywguo
     * @Date: 2020/6/2
     **/
    @ApiOperation("添加")
    @PostMapping("/inserUserDemo")
    public BaseResult inserUserDemo(@RequestBody UserDemo userDemo) {
        return new BaseResult(200, "成功", userDemoService.inserUserDemo(userDemo));
    }


    @RequestMapping(value = "processDiagram")
    public void test02(HttpServletResponse httpServletResponse, String processInstanceId) {
        //1.获取当前的流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        String processDefinitionId = null;
        List<String> activeActivityIds = new ArrayList<>();
        List<String> highLightedFlows = new ArrayList<>();
        //2.获取所有的历史轨迹线对象
        List<HistoricActivityInstance> historicSquenceFlows = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId).activityType(BpmnXMLConstants.ELEMENT_SEQUENCE_FLOW).list();
        historicSquenceFlows.forEach(historicActivityInstance -> highLightedFlows.add(historicActivityInstance.getActivityId()));
        //3. 获取流程定义id和高亮的节点id
        if (processInstance != null) {
            //3.1. 正在运行的流程实例
            processDefinitionId = processInstance.getProcessDefinitionId();
            activeActivityIds = runtimeService.getActiveActivityIds(processInstanceId);
        } else {
            //3.2. 已经结束的流程实例
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            processDefinitionId = historicProcessInstance.getProcessDefinitionId();
            //3.3. 获取结束节点列表
            List<HistoricActivityInstance> historicEnds = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(processInstanceId).activityType(BpmnXMLConstants.ELEMENT_EVENT_END).list();
            List<String> finalActiveActivityIds = activeActivityIds;
            historicEnds.forEach(historicActivityInstance -> finalActiveActivityIds.add(historicActivityInstance.getActivityId()));
        }
        //4. 获取bpmnModel对象
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        //5. 生成图片流
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "jpg", activeActivityIds, highLightedFlows,
                engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(),
                1.0, false);
        byte[] bytes = IoUtil.readInputStream(in, "flow diagram inputStream");
//        httpServletResponse.setContentType("image/jpg");
        ServletOutputStream outputStream = null;
        try {
            outputStream = httpServletResponse.getOutputStream();
            httpServletResponse.reset();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            log.error("生成流程图异常",e);
            e.printStackTrace();

        }
        /*//6. 转化成byte便于网络传输
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = httpServletResponse.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } catch (IOException e) {
            log.error("操作异常",e);
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(in);
        }*/


        log.info("添加表单耗时成功");

    }

    @PostMapping(value = "/test01")
    public void test01() {

    }

}
